layui.config({
    base: '../../layui/' //此处路径请自行处理, 可以使用绝对路径
}).extend({
    formSelects: 'formSelects-v4'
}).use(['jquery', 'formSelects', 'form','layer', 'upload'], function () {
    const form = layui.form
        , layer = layui.layer
        ,upload = layui.upload
        , $ = layui.jquery;
    const token = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxMDcsInVzZXJfa2V5IjoiODRjODg0MmQtZTQ2Ny00ZTVkLTg4NmEtNWE3ZjMxNmNhNTk1IiwidXNlcm5hbWUiOiJkb25nc3M1In0.Oja526u0Twa657h3j3KXJzPI3ESKmTEc1TPt_7fL2yGOys4xSSRsMfLPt_eAscHp6qyox9cqrqnhmCP2Lmgu5A";
//  localhost:9234/unifyWarnReport/alarmReport/excel?beginTime=2001-08-22&endTime=2021-09-14&pageNum=1&pageSize=10
//  localhost:9234/unifyWarnReport/alarmTitle/excel?beginTime=2001-08-22&endTime=2021-08-24
//  localhost:9234/unifyWarnReport/resourceAccess/excel?beginTime=2001-08-22&endTime=2021-09-14&pageNum=1&pageSize=5
//  localhost:9234/unifyWarnReport/functionIndex/excel?beginTime=2021-04-28 14:00:00&projectId=40000002096773
//  localhost:9234/unifyWarnReport/functionIndex/excel?beginTime=2021-04-28 14:00:00&projectId=40000002096773

    // localhost:8083/page/export.html
    // $('body').on('click', '#export1', function () {
    //     location.href = "/unifyWarnReport/alarmReport/excel?beginTime=2001-08-01&endTime=2021-09-15";
    // })
    // $('body').on('click', '#export2', function () {
    //     location.href = "/unifyWarnReport/alarmTitle/excel?beginTime=2001-08-22&endTime=2021-09-15";
    // })
    // $('body').on('click', '#export3', function () {
    //     location.href = "/unifyWarnReport/resourceAccess/excel?beginTime=2001-08-22&endTime=2021-09-15";
    // })
    // $('body').on('click', '#export4', function () {
    //     location.href = "/unifyWarnReport/functionIndex/excel?beginTime=2021-04-28 14:00:00&projectId=40000002096773";
    // })
    $('body').on('click', '#export5', function () {
        var params = {
            content: ""
        };
        $.ajax({
            url: '/student/exportExcelPage?pageNum=1&pageSize=5',
            data: JSON.stringify(params),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            type: "POST",
            responseType: 'blob',
        })
    })


    $('body').on('click', '#export7', function () {
        const  url = '/mapi/flow/onlineCompanyComplaintCollect/exportExcelOnlineSummary';
        const  data = {
            statisticsTime:"2022",
            period:"year",
            type: 0
        };
        const form = $('<form></form>');
        form.attr('action', url + "?rand=" + Math.random());
        form.attr('method', 'post');
        for (const item in data) {
            const input = $('<input type="text" />');
            input.attr('name', item);
            input.attr('value', data[item]);
            form.append(input);
        }
        form.appendTo('body').submit().remove();
    });
    $('body').on('click', '#export9', function () {
        const  url = '/mapi/flow/onlineCompanyComplaintCollect/exportExcelOfflineSummary';
        const  data = {
            statisticsTime:"2021-11",
            period:"month",
            type: 1
        };
        const form = $('<form></form>');
        form.attr('action', url + "?rand=" + Math.random());
        form.attr('method', 'post');
        for (const item in data) {
            const input = $('<input type="text" />');
            input.attr('name', item);
            input.attr('value', data[item]);
            form.append(input);
        }
        form.appendTo('body').submit().remove();
    });
    $('body').on('click', '#export12', function () {
        const  url = '/mapi/cmdb/cmdbData/export/4';
        const  data = {
            pageNum:"1",
            pageSize:"5",
            query: "ip like '%9%' or name like '%u%'",
            columnNames:"name,create_time,update_time,title,code"
        };
        const form = $('<form></form>');
        form.attr('action', url + "?rand=" + Math.random());
        form.attr('method', 'post');
        for (const item in data) {
            const input = $('<input type="text" />');
            input.attr('name', item);
            input.attr('value', data[item]);
            form.append(input);
        }
        form.appendTo('body').submit().remove();
    });
    $('body').on('click', '#export13', function () {
        const  url = '/mapi/cmdb/cmdbData/downloadTemplate/4';
        const  data = {

        };
        const form = $('<form></form>');
        form.attr('action', url + "?rand=" + Math.random());
        form.attr('method', 'post');
        for (const item in data) {
            const input = $('<input type="text" />');
            input.attr('name', item);
            input.attr('value', data[item]);
            form.append(input);
        }
        form.appendTo('body').submit().remove();
    });
    // $('body').on('click', '#export9', function () {
    //     location.href = "/mapi/file/file/download";
    // })

    $('body').on('click', '#export8', function () {
        // const params = new FormData();
        // params.append("filePath","/rtos/online_company/template/线上客服工单报表模板.xlsx");
        // const params2 = {
        //     filePath:"/rtos/online_company/template/线上客服工单报表模板.xlsx?filePath=/rtos/online_company/template/线上客服工单报表模板.xlsx"
        // }
        const url = '/mapi/file/file/download?filePath=/rtos/online_company/template/线上客服工单报表模板.xlsx';
        // $.ajax({
        //     url: url,
        //     // data: params2,
        //     contentType: "application/x-www-form-urlencoded",
        //     type: "POST",
        //     responseType: 'blob',
        //     headers: { Authorization: token }
        // })
        var xhr = new XMLHttpRequest();
        xhr.open("POST",url, true);
        xhr.setRequestHeader("Authorization",token);
        xhr.responseType = "blob";
        xhr.onload = function() {
            if (this.status == 200) {
                $.unblockUI();
                var blob = this.response;
                if(blob.type == "text/html"){
                    return false
                }
                var fileName = "aaaa.xlsx";
                if(window.navigator.msSaveOrOpenBlob){            // IE浏览器下
                    navigator.msSaveBlob(blob, fileName);
                } else {
                    var  link = document.createElement("a");
                    link.href = window.URL.createObjectURL(blob);
                    link.download = fileName;
                    link.click();
                    window.URL.revokeObjectURL(link.href);
                }
            }else{
            }
        }
    })

    //
    // $('body').on('click', '#export8', function () {
    //     const  url = '/mapi/file/file/download';
    //     const  data = {
    //         filePath: "/rtos/online_company/template/线上客服工单报表模板.xlsx"
    //     };
    //     const form = $('<form></form>');
    //     form.attr('action', url + "?rand=" + Math.random());
    //     form.attr('method', 'post');
    //     for (const item in data) {
    //         const input = $('<input type="text" />');
    //         input.attr('name', item);
    //         input.attr('value', data[item]);
    //         form.append(input);
    //     }
    //     form.appendTo('body').submit().remove();
    // })

    $('body').on('click', '#export10', function () {
        const  url = '/mapi/flow/warnInformation/exportExcelPageAll';
        const  data = {
            projectId:"",
            jzywzt:"",
            beginTime: '2022-05-18 17:01:09',
            endTime: '2023-05-25 17:01:09'
        };
        const form = $('<form></form>');
        form.attr('action', url + "?rand=" + Math.random());
        form.attr('method', 'post');
        for (const item in data) {
            const input = $('<input type="text" />');
            input.attr('name', item);
            input.attr('value', data[item]);
            form.append(input);
        }
        form.appendTo('body').submit().remove();
    });

    $('body').on('click', '#export11', function () {
        const  url = '/mapi/flow/jkwarn/export/2';
        const  data = {
            isCurrent: 2,
            projectId:"",
            jzywzt:"",
            beginTime: '2022-05-18 17:01:09',
            endTime: '2023-05-25 17:01:09'
        };
        const form = $('<form></form>');
        form.attr('action', url + "?rand=" + Math.random());
        form.attr('method', 'post');
        for (const item in data) {
            const input = $('<input type="text" />');
            input.attr('name', item);
            input.attr('value', data[item]);
            form.append(input);
        }
        form.appendTo('body').submit().remove();
    })
    //普通图片上传
    var uploadInst = upload.render({
        elem: '#upload'
        // ,url: 'http://10.121.138.143:9204/file/upload?consumer=bigsound&module=banner'
        ,url: 'http://192.168.62.226:10008/mapi/bs/file/upload?consumer=bigsound&module=banner'
        // ,url: 'http://10.121.138.143:10008/mapi/bs/file/upload?consumer=bigsound&module=banner'
        ,accept: 'image/gif,image/jpeg,image/jpg,image/png'
        ,headers: { Authorization: token }
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#photoImg').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //上传成功
            if(res.code == 200){
                layer.msg("上传成功,URL路径为："+res.data.relativeFilePath, {icon: 1, time: 1000})
                layer.msg(res.msg,{icon:1,time:1000},function () {
                    location.reload();
                });
            }else {
                //如果上传失败
                return layer.msg('上传失败');
            }
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });
    //线上导入
    var uploadInst2 = upload.render({
        elem: '#uploadExcel'
        // ,url: 'http://10.121.138.143:9204/file/upload?consumer=bigsound&module=banner'
        ,url: '/mapi/flow/onlineCompanyComplaintCollect/importExcelOnlineSummary/?statisticsTime=2021-11'
        ,accept: 'file' //普通文件
        ,exts: 'xlsx|xls' // 限制文件类型为 xlsx或xls
        // ,url: 'http://10.121.138.143:10008/mapi/bs/file/upload?consumer=bigsound&module=banner'
        ,headers: { Authorization: token }
        ,done: function(res){
            const type = 'auto';
            //上传成功
            if(res.code == 200){
                console.log(res);
                //弹窗确认
                if(res.data.dataExist){
                    layer.open({
                        type: 1
                        ,offset: type //具体配置参考：/docs/modules/layer.html#offset
                        ,id: 'layerDemo'+type //防止重复弹出
                        ,content: '<div style="padding: 20px 20px;width: 300px;height: 50px">'+ res.msg +'</div>'
                        ,btn: '关闭'
                        ,btnAlign: 'r' //按钮居中
                        ,shade: 0 //不显示遮罩
                        ,yes: function(){
                            layer.closeAll();
                        }
                    });
                }else {
                    layer.msg(res.msg,{icon:3,time:1000},function () {
                        location.reload();
                    });
                }
            }else if (res.data && res.data.relativeFilePath){
                const url = "/mapi/flow/onlineCompanyComplaintCollect/importOnlineErrorDetail?filePath="+res.data.relativeFilePath;
                const a = '<a href="'+url+'">导入失败,失败详情</a>';
                layer.open({
                    type: 1
                    ,offset: type //具体配置参考：/docs/modules/layer.html#offset
                    ,id: 'layerDemo'+type //防止重复弹出
                    ,content: '<div style="padding: 20px 100px;">'+ a +'</div>'
                    ,btn: '关闭'
                    ,btnAlign: 'r' //按钮居中
                    ,shade: 0 //不显示遮罩
                    ,yes: function(){
                        layer.closeAll();
                    }
                });
                // //如果上传失败
                // return layer.msg('上传失败');
            }else {
                layer.msg(res.msg,{icon:3,time:3000},function () {
                    location.reload();
                });
            }
        }

    });
    //线下导入
    var uploadInst2 = upload.render({
        elem: '#uploadExcel2'
        // ,url: 'http://10.121.138.143:9204/file/upload?consumer=bigsound&module=banner'
        ,url: '/mapi/flow/onlineCompanyComplaintCollect/importExcelOfflineSummary/?statisticsTime=2021-11'
        ,accept: 'file' //普通文件
        ,exts: 'xlsx|xls' // 限制文件类型为 xlsx或xls
        // ,url: 'http://10.121.138.143:10008/mapi/bs/file/upload?consumer=bigsound&module=banner'
        ,headers: { Authorization: token }
        ,done: function(res){
            const type = 'auto';
            //上传成功
            if(res.code == 200){
                console.log(res);
                //弹窗确认
                if(res.data.dataExist){
                    layer.open({
                        type: 1
                        ,offset: type //具体配置参考：/docs/modules/layer.html#offset
                        ,id: 'layerDemo'+type //防止重复弹出
                        ,content: '<div style="padding: 20px 20px;width: 300px;height: 50px">'+ res.msg +'</div>'
                        ,btn: '关闭'
                        ,btnAlign: 'r' //按钮居中
                        ,shade: 0 //不显示遮罩
                        ,yes: function(){
                            layer.closeAll();
                        }
                    });
                }else {
                    layer.msg(res.msg,{icon:1,time:1000},function () {
                        location.reload();
                    });
                }
            }else {
                const url = "/mapi/flow/onlineCompanyComplaintCollect/importOfflineErrorDetail?filePath="+res.data.relativeFilePath;
                const a = '<a href="'+url+'">导入失败,失败详情</a>';
                layer.open({
                    type: 1
                    ,offset: type //具体配置参考：/docs/modules/layer.html#offset
                    ,id: 'layerDemo'+type //防止重复弹出
                    ,content: '<div style="padding: 20px 100px;">'+ a +'</div>'
                    ,btn: '关闭'
                    ,btnAlign: 'r' //按钮居中
                    ,shade: 0 //不显示遮罩
                    ,yes: function(){
                        layer.closeAll();
                    }
                });
                // //如果上传失败
                // return layer.msg('上传失败');
            }
        }

    });
    var uploadInst3 = upload.render({
        elem: '#uploadExcel3'
        ,url: '/mapi/cmdb/cmdbData/importCmdb/4'
        ,accept: 'file' //普通文件
        ,exts: 'xlsx|xls' // 限制文件类型为 xlsx或xls
        ,headers: { Authorization: token }
        ,done: function(res){
            console.log(res);
            //上传成功
            if(res.code == 200){
                layer.msg(res.msg,{icon:1,time:3000},function () {
                    location.reload();
                });
            }else {
                layer.msg(res.msg,{icon:2,time:3000},function () {
                    location.reload();
                });
            }
        }

    });

    $('body').on('click', '#export14', function () {
        const url = 'http://192.168.29.184:9206/atpTestReport/exportWordDocument';
        $.ajax({
            url: url,
            type: 'POST',
            data:{"reportId":1},
            responseType: 'blob',
            success: function(data, status, xhr) {
                const filename = getFilenameFromContentDisposition(xhr.getResponseHeader('Content-Disposition'));
                const blobUrl = window.URL.createObjectURL(data);
                const link = document.createElement('a');
                link.href = blobUrl;
                link.download = filename;
                document.body.appendChild(link); // 添加链接到 DOM 中，以便触发点击事件
                link.click(); // 触发点击事件
                document.body.removeChild(link); // 从 DOM 中移除链接元素
                window.URL.revokeObjectURL(blobUrl); // 释放链接占用的内存资源
            },
            error: function(xhr, errorType, error) {
                console.error(errorType + ': ' + error);
            }
        });

        function getFilenameFromContentDisposition(contentDisposition) {
            if (!contentDisposition) {
                return '';
            }
            const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
            if (match != null && match[1]) {
                return decodeURIComponent(match[1].replace(/['"]/g, ''));
            } else {
                return '';
            }
        }
    })
});

